package com.example.autumn.jdbc;

import com.example.autumn.annotation.Autowired;
import com.example.autumn.annotation.Bean;
import com.example.autumn.annotation.Configuration;
import com.example.autumn.annotation.Value;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * @author liuzhiyong
 * @date 2023/11/3
 * description: Jdbc配置类
 */
@Configuration
public class JdbcConfiguration {

    /**
     * 数据源
     *
     * @param url 数据库地址
     * @param username 用户名
     * @param password 密码
     * @param driver 驱动
     * @param maximumPoolSize 线程池最大连接数
     * @param minimumPoolSize 线程池最小空闲数
     * @param connTimeout 连接超时时间
     * @return {@link DataSource } 数据源
     * @author liuzhiyong
     * @date 2023/11/3
     */
    @Bean(destroyMethod = "close")
    DataSource dataSource(@Value("${autumn.datasource.url}") String url,
                          @Value("${autumn.datasource.username}") String username,
                          @Value("${autumn.datasource.password}") String password,
                          @Value("${autumn.datasource.driver-class-name}") String driver,
                          @Value("${autumn.datasource.maximum-pool-size:20}") int maximumPoolSize,
                          @Value("${autumn.datasource.minimum-pool-size:1}") int minimumPoolSize,
                          @Value("${autumn.datasource.connection-timeout:30000}") int connTimeout) {
        var config = new HikariConfig();
        config.setAutoCommit(false);
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        if (driver != null) {
            config.setDriverClassName(driver);
        }
        config.setMaximumPoolSize(maximumPoolSize);
        config.setMinimumIdle(minimumPoolSize);
        config.setConnectionTimeout(connTimeout);
        return new HikariDataSource(config);
    }


    @Bean
    JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}
